package com.ruoyi.system.utils;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.phprpc.util.AssocArray;
import org.phprpc.util.PHPSerializer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
public class PhpToJson {

    public static String phpToJson(String phpData) {
        try {
            if (StringUtils.isEmpty(phpData)) {
                return "";
            }

            PHPSerializer phpSerializer = new PHPSerializer();

            AssocArray array = (AssocArray) phpSerializer.unserialize(phpData.getBytes("UTF-8"));
            HashMap<Object, Object> map = array.toHashMap();

            List<HashMap<String, String>> resultList = new ArrayList<>();

            for (Map.Entry<Object, Object> entry : map.entrySet()) {
                AssocArray o = (AssocArray) entry.getValue();

                HashMap<String, Object> myNodeMap = o.toHashMap();
                HashMap<String, String> stringMap = new HashMap<>();

                for (Map.Entry<String, Object> nodeEntry : myNodeMap.entrySet()) {
                    Object value = nodeEntry.getValue();
                    if (value instanceof byte[]) {

                        stringMap.put(nodeEntry.getKey(), new String((byte[]) value, StandardCharsets.UTF_8));
                    } else {

                        stringMap.put(nodeEntry.getKey(), value.toString());
                    }
                }

                resultList.add(stringMap);
            }

            String json = JSON.toJSONString(resultList);

            return json;
        } catch (Exception e) {
            log.info(e.getMessage());
            e.printStackTrace();
        }
        return "";
    }


}
